package com.tancire.quartz.task;

import cn.hutool.core.util.ObjectUtil;
import com.tancire.common.core.redis.RedisCache;
import com.tancire.common.enums.GoodsStatus;
import com.tancire.net.domain.ShopGoods;
import com.tancire.net.service.IShopGoodsService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

import static com.tancire.common.constant.Constants.GOODS_STOCK_PREFIX;

/**
 * 商品定时任务
 *
 * @author chenchao
 */
@Component("goodsTask")
public class GoodsTask {

    @Resource
    private IShopGoodsService shopGoodsService;

    @Resource
    private RedisCache redisCache;

    /**
     * 定时同步商品库存
     * 同步库存用消息队列比较好
     */
    public void asyncGoodsStock() {
        ShopGoods goodsQuery = new ShopGoods();
        goodsQuery.setStatus(GoodsStatus.LISTED.getCode());
        List<ShopGoods> shopGoods = shopGoodsService.selectShopGoodsList(goodsQuery);
        if (ObjectUtil.isNotEmpty(shopGoods)) {
            for (ShopGoods goods : shopGoods) {
                Object cacheObject = redisCache.getCacheObject(GOODS_STOCK_PREFIX + goods.getId());
                if (null != cacheObject) {
                    int count = this.convertToInt(cacheObject);
                    this.shopGoodsService.updateGoodsStock(goods.getId(), count);
                }
            }
        }
    }

    /**
     * 转Int
     *
     * @param cacheObject
     * @return
     */
    private int convertToInt(Object cacheObject) {
        if (null == cacheObject) {
            return 0;
        }
        try {
            return Integer.parseInt((String) cacheObject);
        } catch (Exception e) {
            // 不处理
        }
        return 0;
    }
}
